import Vue from "vue";
import Axios from "axios";
import qs from "qs";
import Cookie from 'js-cookie';
import { refresh } from "less";

// Cookie.set('wxhand-access-token', '', {
//     domain: 'wxhand.com'
// });

let accTokenUrl = "/stuhire/User/refreshToken";
let accessToken = '';
let refreshToken = Cookie.get('wxhand-refresh-token');
let gettingAccToken = false;
let gettingAccTokenTimes = 0;
// Axios.defaults['withCredentials'] = true;

let axios = Axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    transformRequest: [
        function(data, headers) {
            var resData = data;

            if (!(resData instanceof FormData)) {
                resData = qs.stringify(resData);
            }
            return resData;
        },
    ],
    method: "post",
});

axios.interceptors.request.use(
    function(config) {
        // 这里的config包含每次请求的内容
        // 上传文件到又拍云不允许加header
        if (!config.noToken && config.url.indexOf("api.upyun.com") < 0 && accessToken) {
            config.headers["Authorization"] = 'Bearer ' + accessToken;
        }
        return config;
    },
    function(err) {
        return Promise.reject(err);
    }
);

/**
 * @description 增加错误请求重试次数
 *   retry: 2次
 */
// axios.defaults.retry = 2;
// axios.defaults.retryDelay = 1000;
// axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
//     var config = err.config;

//     if(!config || !config.retry) return Promise.reject(err);
//     config.__retryCount = config.__retryCount || 0;
//     if(config.__retryCount >= config.retry) {
//         return Promise.reject(err);
//     }
//     config.__retryCount += 1;

//     var backoff = new Promise(function(resolve) {
//         setTimeout(function() {
//             resolve();
//         }, config.retryDelay || 1);
//     });
//     return backoff.then(function() {
//         return axios(config);
//     });
// });

function goLogin() {
    // TODO 跳转统一登录
    console.log('这里在跳转login----------------------------');
    location.href = process.env.VUE_APP_HOME_HOST + '/login?dist='+escape(location.href);
}

// 从cookie中获取token
function getTokenLocal() {
    if (!accessToken) {
        accessToken = Cookie.get('wxhand-access-token');
    }

    return accessToken;
}

// 远程获取accessToken
function getAccessToken(noLogin) {
    console.log('refreshTOken', refreshToken);
    axios.post(accTokenUrl, {
        noToken: true,
        noPrefix: true,
        refreshToken: refreshToken
    }).then(function (resp) {
        console.log('refresh token', resp);
        if (!noLogin && resp.status != 200) {
            goLogin();
        }
        if (resp.data.code == 1) {
            let token = resp.data.data.access_token;
            let refreshToken = resp.data.refresh_token;

            Cookie.set('wxhand-access-token', token, {
                domain: 'wxhand.com'
            });
            Cookie.set('wxhand-refresh-token', refreshToken, {
                domain: 'wxhand.com'
            });
            accessToke = token;
        } else if (!noLogin) {
            goLogin();
        }
    });
}

/** 获取token */
function getToken(callback) {
    let st = "";

    if (gettingAccToken) {
        setTimeout(function() {
            callback("");
        }, 200);
        return;
    }
    st = getTokenLocal();
    if (st) {
        callback(st);
    } else {
        getAccessToken();
    }
}

/**
 * 处理请求返回结果
 * @param resp axios返回原始数据,
 * @param instance 调用接口原始vue实例
 */
function dealResponse(resp, options) {
    if (resp.status != "200") {
        return Promise.reject(res);
    }

    let instance = options.instance;

    // accessToken缺失或者失效, 需要跳转登录
    if (resp.data.code == 1001) {
        getAccessToken();
        return;
    }

    // 未登录
    if (resp.data.code == 1002) {
        getAccessToken();
        return;
    }

    // 其它地方登录
    if (resp.data.code == 1003) {
        // instance.$router.replace({
        //     path: "/Login?target=quit",
        // });
        goLogin();
        return;
    }

    //密码已修改
    if (resp.data.code == 1004) {
        goLogin();
        return;
    }
    if (options.success) {
        options.success(resp.data);
    }
}

/** 清除客户端保留token */
function clearToken() {
    let token = Cookie.get('wxhand-access-token');
    if (accessToke == token) {
        Cookie.set('wxhand-access-token', '', {
            domain: 'wxhand.com'
        });
    }
    accessToke = undefined;
}

/** 手动设置token */
function setToken(token) {
    accessToke = token;
    // 本地存储 防止出现覆盖管理员身份,只是保存临时变量,刷新丢失
    // Cookie.set('wxhand-access-token', accessToken, {
    //     domain: 'wxhand.com'
    // });
}

/**
 * 一般post请求
 * @param
 */
function post(url, data, success, fail, token) {
    let instance = this;

    // console.log('===========env: ', process.env.VUE_APP_HOME_HOST);
    let st = token;
    if (!data.noToken && !st && url != accTokenUrl) {
        getToken(function(currTicket) {
            instance.$post(url, data, success, fail, currTicket);
        });
    } else {
        let postUrl = url;
        if (!data.noPrefix) {
            postUrl = '/stuhire_shop' + postUrl;
        }
        axios
            .post(postUrl, data)
            .then(function(resp) {
                dealResponse(resp, {
                    instance,
                    url,
                    data,
                    success,
                    fail,
                });
            })
            .catch(function(err) {
                if (fail) {
                    fail(err);
                }
                return Promise.reject(err);
            });
    }
}

/**
 * 上传文件请求
 * @param options 请求相关配置{url, data, progress(上传进度), success, fail}
 * @param session_ticket ticket
 */
function upload(options, token) {
    let instance = this;

    let st = token;

    if (!st && options.url != accTokenUrl) {
        getToken(function(currTicket) {
            instance.$upload(options, currTicket);
        });
    } else {
        let postUrl = options.url;
        if (!data.noPrefix) {
            postUrl = '/stuhire_shop' + postUrl;
        }
        axios
            .post(postUrl, options.data, {
                onUploadProgress: function(e) {
                    if (e.total > 0) {
                        e.percent = (e.loaded / e.total) * 100;
                    }
                    if (options.progress) {
                        options.progress(e);
                    }
                },
            })
            .then(function(resp) {
                dealResponse(resp, {
                    instance,
                    url: options.url,
                    data: options.data,
                    success: options.success,
                    fail: options.success,
                });
            })
            .catch(function(err) {
                if (options.fail) {
                    options.fail(err);
                }
                return Promise.reject(err);
            });
    }
}

function install(Vue, options) {
    Vue.axios = Axios;

    Object.defineProperties(Vue.prototype, {
        $post: {
            get() {
                return post.bind(this);
            },
        },
        $goLogin: {
            get() {
                return goLogin.bind(this);
            },
        },
        $upload: {
            get() {
                return upload.bind(this);
            },
        },
        axios: {
            get() {
                return axios;
            },
        }
    });
}

export default {
    install
};
